package com.javatiaocao.myblog.service.impl;

import com.javatiaocao.myblog.constant.CodeType;
import com.javatiaocao.myblog.mapper.UserDao;
import com.javatiaocao.myblog.mapper.UserMapper;
import com.javatiaocao.myblog.model.BlogUser;
import com.javatiaocao.myblog.model.Role;
import com.javatiaocao.myblog.model.User;
import com.javatiaocao.myblog.model.UserDTO;
import com.javatiaocao.myblog.service.UserService;
import com.javatiaocao.myblog.utils.DataMap;
import com.javatiaocao.myblog.utils.JsonResult;
import com.javatiaocao.myblog.utils.MD5Util;
import org.apache.commons.lang.ObjectUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;


    @Autowired
    private UserDao userDao;
    @Override
    public boolean save(BlogUser user) {
        return userDao.save(user);
    }

    @Override
    public boolean update(BlogUser user) {
        return userDao.update(user);
    }

    @Override
    public boolean delete(Integer id) {
        return userDao.delete(id);
    }

    @Override
    public BlogUser get(Integer id) {
        return userDao.get(id);
    }

    @Override
    public User findByPhone(String phone) {
        return userMapper.findUserByPhone(phone);
    }


    //注册
    @Override
    @Transactional
    public DataMap register(User user) {
        //判断用户名异常
        if(user.getUsername().length() > 35){
            return DataMap.fail(CodeType.USERNAME_FORMAT_ERROR);
        }

        //判断用户名
        if (userMapper.findExistUsername(user.getUsername()) != null){
            return DataMap.fail(CodeType.USERNAME_EXIST);
        }

        //加密密码
        MD5Util md5Util = new MD5Util();
        user.setPassword(md5Util.encode(user.getPassword()));

        //判断手机存在
        if(userMapper.findExistPhone(user.getPhone()) != null){
            return DataMap.fail(CodeType.PHONE_EXIST);
        }

        //头像
        if("male".equals(user.getGender())){
            user.setAvatarImgUrl("www.javatiaocao.com");
        } else if ("female".equals(user.getGender())) {
            user.setAvatarImgUrl("www.javatiaocao.com");
        }
        //注册
        userMapper.register(user);
        User userByPhone = userMapper.findUserByPhone(user.getPhone());
        updateRoleById(userByPhone.getId(),1);
        return DataMap.success();
    }

    private void updateRoleById(int id, int roleId) {
        userMapper.updateRoleById(id,roleId);
    }

    @Override
    public UserDTO findExistUsername(String username) {
        return userMapper.findExistUsername(username);
    }


    @Override
    public DataMap login(UserDTO userDTO, HttpSession session) {
        //判断用户名是否存在
        if (userMapper.findExistPhone(userDTO.getUsername()) == null){
            return DataMap.fail(CodeType.USERNAME_NOT_EXIST);
        } else if (userDTO.getUsername() == null) {
            return DataMap.fail(CodeType.USERNAME_BLANK);
        }

        MD5Util md5Util = new MD5Util();
        userDTO.setPassword(md5Util.encode(userDTO.getPassword()));
        String phone = userDTO.getUsername();
        String password = userDTO.getPassword();
        String password1 = userMapper.findPasswordByPhone(phone);
        //判断密码是否正确
        if (!password1.equals(password)){
            return DataMap.fail(CodeType.USER_NOT_LOGIN);
        }
        User loginUser = userMapper.findUserByPhone(userDTO.getUsername());
        session.setAttribute("loginUser",loginUser);

        return DataMap.success();
    }

    @Override
    public DataMap changePasswordByPhone(String phone, String newPassword) {
        //判断手机是否存在
        if (userMapper.findExistPhone(phone) == null){
            return DataMap.fail(CodeType.PHONE_ERROR);
        }
        //新密码加密
        MD5Util md5Util = new MD5Util();
        String newMD5Password = md5Util.encode(newPassword);
        //修改密码
        userMapper.changePasswordByPhone(phone,newMD5Password);
        return DataMap.success();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities(int id) {
        List<GrantedAuthority> list = new ArrayList<>();
        int roleId = userMapper.getRoleIdByUid(id);
        String role = userMapper.getRoleByRoleId(roleId);
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                return role;
            }
        });
        return list;
    }

    @Override
    public DataMap canYouWrite(UserDetails userDetails) {
        List<Role> roleList = userMapper.findUserRoleByPhone(userDetails.getUsername());
        int isPermissions = 0;
        for (Role role : roleList) {
            if (role.getName().equals("ROLE_SUPERADMIN")){
                isPermissions += 1;
            } else if (role.getName().equals("ROLE_ADMIN")) {
                isPermissions += 1;
            }
        }

        //权限判断
        if (isPermissions >= 1){
            return DataMap.success();
        }

        return DataMap.fail(CodeType.USER_NOT_LOGIN);
    }

    @Override
    public DataMap getUserPersonalInfo(String phone) {
        User user = userMapper.getUserPersonalInfo(phone);

        return DataMap.success().setData(user);
    }


}
